<template>
  <div class="login-card">
    <div class="login-card-tabs">
      <el-tabs v-model="currentTab" class="demo-tabs" @tab-change="handleTabChange">
        <el-tab-pane label="验证码登录" name="code">
          <div class="form">
            <el-form
              ref="codeFormRef"
              :model="formData.codeForm"
              :rules="formRules.codeFormRules"
              @submit.prevent
            >
              <el-form-item prop="phone">
                <span class="tip">手机号</span>
                <el-input
                  v-model.number="formData.codeForm.phone"
                  type="text"
                  autocomplete="off"
                  placeholder="输入手机号"
                  maxlength="11"
                >
                  <template #prepend>
                    <el-select
                      class="prepend"
                      v-model="phonePrependVal"
                      popper-class="popperPrepend"
                    >
                      <template v-for="prependItem in phonePrepend" :key="prependItem.id">
                        <el-option :label="prependItem.label" :value="prependItem.value" />
                      </template>
                    </el-select>
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item prop="image_code">
                <span class="tip">验证码</span>
                <el-input
                  v-model.trim="formData.codeForm.image_code"
                  type="text"
                  autocomplete="off"
                  placeholder="输入图像验证码"
                  maxlength="6"
                >
                  <template #append>
                    <img
                      class="append"
                      @click="handleResetVerifyCode"
                      :src="verificationCodePhoto"
                      alt="验证码加载中..."
                    />
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item prop="phone_code">
                <el-input
                  v-model.trim="formData.codeForm.phone_code"
                  type="text"
                  autocomplete="off"
                  placeholder="输入短信验证码"
                  maxlength="6"
                >
                  <template #suffix>
                    <button class="suffix" @click.stop="handleCodeBtnClick">
                      {{ codeBtnShow }}
                    </button>
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item>
                <el-checkbox class="agree" v-model="isAgree" size="large">
                  阅读并同意<i class="primary-color">AImunity协议</i>及<i class="primary-color"
                    >隐私保护声明</i
                  >
                </el-checkbox>
              </el-form-item>
            </el-form>

            <button class="form-submit" @click="handleCodeFormSubmit">登录/注册</button>
          </div>
        </el-tab-pane>

        <el-tab-pane label="密码登录" name="password">
          <div class="form">
            <el-form
              ref="passwordFormRef"
              :model="formData.passwordForm"
              :rules="formRules.passwordFormRules"
              @submit.prevent
            >
              <el-form-item prop="phone">
                <span class="tip">输入手机号或邮箱</span>
                <el-input
                  v-model.trim="formData.passwordForm.phone"
                  type="text"
                  autocomplete="off"
                  placeholder="输入手机号"
                  maxlength="24"
                >
                </el-input>
              </el-form-item>

              <el-form-item prop="password">
                <div class="tip">
                  <span>Password</span>
                  <span class="tip-forgot" @click="handleForgotBtnClick">Forgot?</span>
                </div>
                <el-input
                  v-model.trim="formData.passwordForm.password"
                  type="password"
                  autocomplete="off"
                  placeholder="Enter your password"
                  show-password
                  maxlength="24"
                >
                </el-input>
              </el-form-item>
            </el-form>

            <button class="form-submit2" @click="handlePasswordFormSubmit">登录账号</button>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>

  <my-dialog ref="dialogRef" :dialog-class="'checkMsDialog'">
    <template #default>
      <div class="dialog-main">
        <div class="main-title">身份验证</div>

        <div class="main-subtitle">请验证身份后，再进行下一步操作</div>

        <div class="main-imagecode">
          <span class="tip">验证码</span>

          <el-input
            class="ipt"
            v-model.trim="dialogImageCode"
            type="text"
            autocomplete="off"
            placeholder="输入图像验证码"
            maxlength="6"
          >
            <template #append>
              <img
                class="append"
                @click="handleResetVerifyCode"
                :src="verificationCodePhoto"
                alt="验证码加载中..."
              />
            </template>
          </el-input>
        </div>

        <div class="main-tip">
          使用手机号 <span class="phone-font">{{ formData.passwordForm.phone }}</span> 验证
        </div>

        <div class="main-code">
          <el-input
            class="ipt"
            type="text"
            v-model="dialogCode"
            autocomplete="off"
            placeholder="输入短信验证码"
            maxlength="6"
          >
            <template #suffix>
              <button class="suffix" @click.stop="handleDialogCodeBtnClick">
                {{ codeBtnShow2 }}
              </button>
            </template>
          </el-input>
        </div>

        <div class="main-action hover-half" @click="handleDialogConfirm">验证</div>
      </div>
    </template>
  </my-dialog>
</template>

<script lang="ts" setup>
import useCodeCount from '@/hooks/useCodeCount'
import useRouterJump from '@/hooks/useRouterJump'
import useLoginStore from '@/stores/login/login'
import useProfileStore from '@/stores/profile/profile'
import { ElMessage } from 'element-plus'
import { storeToRefs } from 'pinia'
import { reactive, ref, computed } from 'vue'

const profileStore = useProfileStore()

// ====== data
const dialogRef = ref<any>(null)
const codeFormRef = ref<any>()
const passwordFormRef = ref<any>()
const isAgree = ref<boolean>(false)
const currentTab = ref<'code' | 'password'>('code')
const phonePrependVal = ref<any>('中国大陆+86')
const phonePrepend = ref([
  {
    id: 1,
    value: '+86',
    label: '中国大陆+86'
  },
  {
    id: 2,
    value: '+886',
    label: '中国台湾+886'
  },
  {
    id: 3,
    value: '+852',
    label: '中国香港+852'
  },
  {
    id: 4,
    value: '+853',
    label: '中国澳门+853'
  }
])
const dialogCode = ref<string>('')
const dialogImageCode = ref<string>('')
const formData = reactive<any>({
  codeForm: {
    phone: '',
    phone_code: '',
    image_code: ''
  },
  passwordForm: {
    phone: '',
    password: ''
  }
})
const formRules = reactive<any>({
  codeFormRules: {
    phone: [
      { required: true, message: '请输入手机号码', trigger: 'blur' },
      { type: 'number', message: '请检查手机号码是否有误', trigger: 'blur' }
    ],
    image_code: [{ required: true, message: '请输入图像验证码', trigger: 'blur' }],
    phone_code: [{ required: true, message: '请输入短信验证码', trigger: 'blur' }]
  },
  passwordFormRules: {
    phone: [{ required: true, message: '请输入手机号码', trigger: 'blur' }],
    password: [{ required: true, message: '请输入用户密码', trigger: 'blur' }]
  }
})
let verifyCodeTimer: any = null

// ====== hooks
const loginStore = useLoginStore()
const { verificationCodePhoto, currentCardType } = storeToRefs(loginStore)
const { codeBtnShow, startCounting, isCounting } = useCodeCount(60)
const {
  codeBtnShow: codeBtnShow2,
  startCounting: startCounting2,
  isCounting: isCounting2
} = useCodeCount(60)

// ====== computed
const phoneCpt = computed(
  () => formData.passwordForm.phone.slice(0, -8) + '****' + formData.passwordForm.phone.slice(-4)
)

// ====== methods
const handleTabChange = (name: string) => {
  name === 'code' ? codeFormRef.value?.resetFields() : passwordFormRef.value?.resetFields()
  resetFormData()
}
const handleCodeBtnClick = () => {
  if (!formData.codeForm.phone) {
    ElMessage.warning('请填写手机号码')
    return
  } else if (!formData.codeForm.image_code) {
    ElMessage.warning('请填写图形验证码')
    return
  } else if (isCounting.value) {
    return
  }

  loginStore.smsAction(
    {
      phone: formData.codeForm.phone,
      verifyCode: formData.codeForm.image_code
    },
    () => {
      startCounting()
    }
  )
}
const handleForgotBtnClick = () => {
  if (!formData.passwordForm.phone) {
    ElMessage.warning('请先填写手机号码')
    return
  }
  dialogRef.value?.openDialog()
  handleResetVerifyCode()
}
const handleCodeFormSubmit = () => {
  codeFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (!isAgree.value) {
        ElMessage({
          message: '请仔细阅读并勾选协议政策',
          type: 'warning'
        })
      } else {
        loginStore.addUserAction(
          {
            phone: formData.codeForm.phone,
            code: formData.codeForm.phone_code
          },
          res => {
            if (res.result.secret) {
              currentCardType.value = 'register'
            } else {
              // 获取用户信息
              profileStore.selectInfoAction({})
              useRouterJump('/')
            }
          }
        )
      }
    } else {
      console.log('error submit!')
      return false
    }
  })
}
const handlePasswordFormSubmit = () => {
  passwordFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      loginStore.loginAction(
        {
          phone: formData.passwordForm.phone,
          password: formData.passwordForm.password
        },
        () => {
          useRouterJump('/')
        }
      )
    } else {
      return false
    }
  })
}
const handleResetVerifyCode = () => {
  if (verifyCodeTimer) return

  verifyCodeTimer = setTimeout(() => {
    clearTimeout(verifyCodeTimer)
    verifyCodeTimer = null
  }, 2000)

  loginStore.getVerificationCodePhotoAction()
}
const handleDialogCodeBtnClick = () => {
  if (isCounting2.value) {
    return
  } else if (!dialogImageCode.value) {
    ElMessage.warning('请输入图形验证码')
    return
  }
  loginStore.smsOneAction(
    {
      phone: formData.passwordForm.phone,
      verifyCode: dialogImageCode.value
    },
    () => {
      startCounting2()
    }
  )
}
const handleDialogConfirm = () => {
  if (!dialogCode.value) {
    ElMessage({ message: '请输入短信验证码', type: 'warning' })
    return
  } else if (!dialogImageCode.value) {
    ElMessage.warning('请输入图形验证码')
    return
  }

  loginStore.checkMsAction(
    {
      phone: formData.passwordForm.phone,
      code: dialogCode.value
    },
    () => {
      dialogCode.value = ''
      dialogImageCode.value = ''
      dialogRef.value?.closeDialog(() => {
        currentCardType.value = 'forgot'
      })
    }
  )
}

// ====== tool
function resetFormData() {
  phonePrependVal.value = '中国大陆+86'
  isAgree.value = false
}
function setupInit() {
  loginStore.getVerificationCodePhotoAction()
}

// ====== lifecycle
setupInit()
</script>

<style lang="less" scoped>
@import '@/assets/css/index.less';

.login-card {
  :deep(.login-card-tabs) {
    .el-tabs__header {
      margin: 0;

      .el-tabs__nav-wrap::after {
        display: none;
      }

      .el-tabs__item {
        font-size: 32px;
        font-weight: 600;
        color: #666666;
        padding: 0 119px 8px 0;

        &.is-active {
          color: #0a0a0a;
        }
      }

      .el-tabs__active-bar {
        background-color: #0075ff;
        height: 4px;
      }
    }

    .el-tabs__content {
      width: 485px;
    }
  }

  .form {
    margin-top: 29px;

    :deep(.el-form-item) {
      margin-bottom: 23px;

      .tip {
        display: flex;
        justify-content: space-between;
        width: 100%;
        font-size: 19px;
        line-height: 1;
        font-weight: 400;
        color: #5a5a5d;
        margin-bottom: 15px;

        .tip-forgot {
          color: #007dfa;
          cursor: pointer;
        }
      }

      .el-input {
        height: 58px;
        font-size: 17px;
      }

      .el-input-group__prepend,
      .el-input-group__append {
        background-color: #ffffff;
        box-shadow: none;
      }

      .prepend {
        .el-input__inner {
          text-align: center;
          font-size: 16px;
          width: 120px;
        }
      }

      .append {
        width: 124px;
        height: 43px;
        cursor: pointer;
      }

      .suffix {
        display: flex;
        justify-content: center;
        align-items: center;
        border: none;
        background: none;
        font-size: 17px;
        font-weight: 400;
        color: #0075ff;
        cursor: pointer;
      }

      .agree {
        font-weight: 500;
        color: #999999;
        margin-top: 5px;

        .el-checkbox__input.is-checked + .el-checkbox__label {
          color: #999999;
          font-size: 20px;
        }
        .el-checkbox__inner {
          width: 21px;
          height: 21px;
        }
        .el-checkbox__inner::after {
          width: 6px;
          height: 12px;
          left: 6px;
        }
        .el-checkbox__label {
          font-size: 20px;
        }
      }
    }

    .form-submit,
    .form-submit2 {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 58px;
      background: #007dfa;
      font-size: 20px;
      font-weight: 600;
      color: #ffffff;
      border: none;
      border-radius: 10px;
      transition: all 0.3s ease;
      margin-top: 36px;
    }
    .form-submit:hover,
    .form-submit2:hover {
      opacity: 0.7;
    }

    .form-submit2 {
      margin-top: 40px;
    }
  }
}

.primary-color {
  position: relative;
  color: @primary-color;
}
.primary-color::after {
  content: '';
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 1px;
  background-color: #0075ff;
}

:global(.popperPrepend) {
  text-align: center;
}

.checkMsDialog {
  :global(.checkMsDialog-container) {
    width: 540px;
    height: 580px;
  }

  .dialog-main {
    display: flex;
    flex-direction: column;
    align-items: center;
    overflow: hidden;
    box-sizing: border-box;
    padding: 0 40px;

    .main-title {
      font-size: 37px;
      margin-top: 63px;
    }

    .main-subtitle {
      font-size: 17px;
      color: #666666;
      margin-top: 20px;
    }

    .main-imagecode {
      margin-top: 20px;
      width: 100%;

      .tip {
        font-size: 17px;
        line-height: 28px;
        align-self: flex-start;
        margin-top: 35px;
      }

      .append {
        width: 140px;
        height: 45px;
        margin-left: 10px;
        cursor: pointer;
      }

      :deep(.ipt) {
        width: 100%;
        height: 59px;
        border-radius: 10px;
        font-size: 17px;
        font-weight: 400;
        margin-top: 10px;

        input::input-placeholder {
          font-size: 17px;
          color: #bebebf;
        }
        input::-webkit-input-placeholder {
          font-size: 17px;
          color: #bebebf;
        }
        input::-moz-placeholder {
          font-size: 17px;
          color: #bebebf;
        }
        input:-moz-placeholder {
          font-size: 17px;
          color: #bebebf;
        }
        input::-ms-input-placeholder {
          font-size: 17px;
          color: #bebebf;
        }
      }
      :deep(.el-input-group__append) {
        padding: 0;
        background: none;
        border: none;
        box-shadow: none;
      }
    }

    .main-tip {
      font-size: 17px;
      line-height: 28px;
      align-self: flex-start;
      margin-top: 35px;

      .phone-font {
        text-decoration: underline;
      }
    }

    .main-code {
      margin-top: 10px;
      width: 100%;

      :deep(.ipt) {
        width: 100%;
        height: 59px;
        border-radius: 10px;
        font-size: 17px;
        font-weight: 400;

        input::input-placeholder {
          font-size: 17px;
          color: #bebebf;
        }
        input::-webkit-input-placeholder {
          font-size: 17px;
          color: #bebebf;
        }
        input::-moz-placeholder {
          font-size: 17px;
          color: #bebebf;
        }
        input:-moz-placeholder {
          font-size: 17px;
          color: #bebebf;
        }
        input::-ms-input-placeholder {
          font-size: 17px;
          color: #bebebf;
        }
      }

      .suffix {
        display: flex;
        justify-content: center;
        align-items: center;
        border: none;
        background: none;
        font-size: 17px;
        font-weight: 400;
        color: #0075ff;
        cursor: pointer;
      }
    }

    .main-action {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 264px;
      height: 45px;
      background: #0075ff;
      box-shadow: 0px 3px 3px 0px rgba(0, 0, 0, 0.1);
      border-radius: 7px;
      font-size: 17px;
      color: #ffffff;
      margin-top: 87px;
    }
  }
}
</style>
